package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.web.customargument.bind.annotation.IfNeedLogin;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Semester;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.*;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.zyc.*;
import cn.qidisoft.edu.hzjt.utils.LogType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 党员个人先锋指数
 * 
 * @author zhangwenliang
 * @date 2018.11.24
 */
@Controller
@RequestMapping(value = "/dyxfzs/")
@IfNeedLogin(needLogin = true)
public class DyxfzsController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	 @Autowired
	 private IDyService dyService;
	 
	 @Autowired
	 private  IDzbService dzbService;

	 @Autowired
	 private IDyxfzsService dyxfzsService;
	 
	 @Autowired
	 private IEmpService empService;
	 
	 @Autowired
	 private IStudentService studentService;
	 
	 @Autowired
	 private ICommonService commonService;
	 /**
	 * 跳转到党员先锋指数列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(ModelMap model,HttpServletRequest request) {
		// 获取党支部信息
		PartyBranch  partyBranch = new PartyBranch();
		List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
		request.setAttribute("pList", pList);
		// 获取学期信息
		BaseController.getSemesterList(model, commonService);
		// 获取当前学期信息
		BaseController.getSemester(model, commonService);
		return "zyc/dyxfzs/list"; 
	}
     /**
      * 获取列表分页数据
      * @param model
      * @param request
      * @param pageSize
      * @param currentPage
      * @param partyBranch
      * @return
      */
	@RequestMapping(value="getListData",method=RequestMethod.POST)
	@ResponseBody
	public ResponseResult getListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyLeagueMember PartyLeagueMember) {
		System.out.println(pageSize + currentPage);
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "rDRQ", "asc");
		PartyLeagueMember.setOrderField((String) request.getAttribute("orderField"));
		PartyLeagueMember.setOrderFlag((String) request.getAttribute("orderFlag"));
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String semId = request.getParameter("semId");
	    queryMap.put("partyLeagueMember", PartyLeagueMember);
		queryMap.put("semId", semId);
		PaginationBean<PartyMemberEvaluation> paginationBean = dyxfzsService.getListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}
	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value ="preadd")
	@Token(save = true)
	public String preadd(ModelMap model, HttpServletRequest request) {
		try {
			// 查询评定学期 4）下拉选项，默认为当前学期（数据表BD_Semester中CurrentXQ=1对应的记录）
			// 获取学期信息
			BaseController.getSemesterList(model, commonService);
			// 获取当前学期信息
			BaseController.getSemester(model, commonService);
			// 获取党支部信息
			PartyBranch  partyBranch = new PartyBranch();
			List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
			request.setAttribute("pList", pList);
			// 得到所有项目
			List<PartyEvalItem> partyEvalItems =  dyxfzsService.getListGrade();
			Integer ItemNum = partyEvalItems.size();
			request.setAttribute("ItemNum", ItemNum);
			return "zyc/dyxfzs/add";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	
	/**
	 * 获得所以党员JSON集合数据  (打分详情)
	 * @param model
	 * @param request
	 * @param pageSize
	 * @param currentPage
	 * @return
	 */
	@RequestMapping(value="getDyScoreListData",method=RequestMethod.POST)
	@ResponseBody
	public ResponseResult getDyScoreListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyLeagueMember partyLeagueMember) {
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 40 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "dYID", "asc");
		partyLeagueMember.setOrderField((String) request.getAttribute("orderField"));
		partyLeagueMember.setOrderFlag((String) request.getAttribute("orderFlag"));
		Map<String, Object> queryMap = new HashMap<String, Object>();
		String semId = request.getParameter("semId");
		String dZBID = request.getParameter("dZBID");
		String xM = request.getParameter("xM");
		if(xM != null) {
			queryMap.put("xM", xM.trim());						
		}
		queryMap.put("dZBID", dZBID);
	    queryMap.put("partyLeagueMember", partyLeagueMember);
//		queryMap.put("semId", semId);
		PaginationBean<PartyLeagueMember> paginationBean = dyxfzsService.getdyGardeListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}	
	
	/**
	 * 添加个人先锋指数信息
	 * @param model
	 * @param request
	 * @param scoreData
	 * @return
	 */
	@RequestMapping(value = "insert",method=RequestMethod.POST)
	public String insert(ModelMap model, HttpServletRequest request, ScoreData scoreData) {
		try {
			// 获取当前系统用户
			UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			// 添加 HZJT_ZHDJ_PartyMemberEvaluation —— 党员先锋指数基本信息表
			String semId = request.getParameter("semId");
			Double[] score = scoreData.getScores(); 
			Integer[] dYID = scoreData.getDyIds();
			Integer[] dZBID = scoreData.getdZBID();
			Integer[] itemId = scoreData.getItems();
			// 获取项目个数项目
			List<PartyEvalItem> partyEvalItems =  dyxfzsService.getListGrade();
			Integer itemCount =  partyEvalItems.size();
			int count = 0;
			Map<String, Object> qMap = new HashMap<String, Object >();
			for(int i = 0; i < score.length;i++) {
				if((i+1)%itemCount == 0) {
					count++;
					if(null !=score[i -2] || null != score[i-1] || null != score[i]) {
						// 添加党员先锋指数表
						PartyMemberEvaluation pEvaluation = new PartyMemberEvaluation();
						pEvaluation.setgID("1");
						pEvaluation.setSemId(Integer.parseInt(semId));
						pEvaluation.setdYID(dYID[i]);
						Double scored = 0.0;
						if(null != score[i-2]) {
							scored += score[i-2];
						}
						if(null != score[i-1]) {
							scored += score[i-1];
						}
						if(null != score[i]) {
							scored += score[i];
						}
						pEvaluation.setTotalScore(scored);
						pEvaluation.setRemark("");
						pEvaluation.setCreatorId(user.getUid());
						pEvaluation.setCreatorName(user.getXm());
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String formatStr =formatter.format(new Date());
						pEvaluation.setCreateTime(formatStr);
						// 添加党员先锋指数信息
						PartyMemberEvaluation pEvaluation2 = dyxfzsService.selectEval(pEvaluation);
						if(null != pEvaluation2) {
							pEvaluation.setzSID(pEvaluation2.getzSID());
							dyxfzsService.updateDyxfzsinfo(pEvaluation);
						} else {
							dyxfzsService.insert(pEvaluation);							
						}
						for(int j = i-2; j < itemCount*count; j++) { 
							// 判断是否存在
							// 添加 明细得分表
							PartyMemberEvalScore pEvalScore = new PartyMemberEvalScore();
							pEvalScore.setParentId(pEvaluation.getzSID());
							pEvalScore.setItemId(itemId[j]);
							if(null != score[j]) {
								pEvalScore.setScore(score[j]);								
								qMap.put("itemId", itemId[j]);
								qMap.put("parentId", pEvaluation.getzSID());
								PartyMemberEvalScore pScore = dyxfzsService.selectScore(qMap);
								if(null != pScore) {
									// 更新明细得分表
									pEvalScore.setScoreId(pScore.getScoreId());
									dyxfzsService.updateScore(pEvalScore);
								} else {
									// 添加明细得分表
									dyxfzsService.insertScore(pEvalScore);
								}
							}
							
						}
						
					}
					
				}
				
			}
			return "redirect:preadd";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	/**
	 * 跳转到修改页面
	 * 编辑该党员的明细打分页面，仅浏览、编辑一个人的打分信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("edit")
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String  zSID = request.getParameter("zSID");
			Map<String, Object> queryMap = new HashMap<String, Object>();
			PartyLeagueMember partyLeagueMember = new PartyLeagueMember();
		    queryMap.put("zSID", zSID);
		    queryMap.put("partyLeagueMember", partyLeagueMember);
			List<PartyMemberEvaluation> datalist = dyxfzsService.getDybList(queryMap);
			request.setAttribute("PartyMemberEvaluation", datalist.get(0));
			List<Semester> sList =  new ArrayList<Semester>();
			for(int i = 0; i < datalist.size(); i++) {
				Semester semester = dyxfzsService.queryByPK(datalist.get(i).getSemId());	
				sList.add(semester);
			}
			// 得到所有打分项
			List<PartyEvalItem> evalItems = dyxfzsService.getListGrade(); 
			request.setAttribute("sList", sList);
			request.setAttribute("evalItems", evalItems);
			return "zyc/dyxfzs/edit";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	
	/**
	 * 进入预览页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("view")
	public String view(ModelMap model, HttpServletRequest request) {
		try {
			UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String  zSID = request.getParameter("zSID");
			String dYID = request.getParameter("dYID");
			String gH = user.getEmid()+"";
			request.setAttribute("zSID", zSID);
			request.setAttribute("dYID", dYID);
			request.setAttribute("gH", gH);
			// 获取学期信息
			BaseController.getSemesterList(model, commonService);
			// 获取当前学期信息
			BaseController.getSemester(model, commonService);
			return "zyc/dyxfzs/view";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	@RequestMapping(value="getItemScore")
	@ResponseBody
	public List<PartyMemberEvalScore> getItemScore(HttpServletRequest request) {
		String zSID = request.getParameter("zSID");
		String semId = request.getParameter("semId");
		String dYID = request.getParameter("dYID");
		String gH = request.getParameter("gH");
		Map<String, Object> qMap = new HashMap<String, Object>();
		qMap.put("zSID", zSID);
		qMap.put("semId", semId);
		qMap.put("dYID", dYID);
		qMap.put("gH", gH);
		// 得到所有项目
		List<PartyMemberEvalScore> pEvalScores = dyxfzsService.getScoreList(qMap);
		return pEvalScores;
	}
	
	/**
	 * 更新党员个人先锋指数信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value ="update",method=RequestMethod.POST)
	public String update(HttpServletRequest request,  PartyMemberEvaluation partyMemberEvaluation) {
	  try {
		    // 更新个人先锋指数
		    if(dyxfzsService.updateDyxfzsinfo(partyMemberEvaluation) > 0) {
		    	Map<String, Object> queryMap = new HashMap<String, Object>();
				// 查询党员信息
		    	PartyLeagueMember partyLeagueMember = new PartyLeagueMember();
			    queryMap.put("zSID", partyMemberEvaluation.getzSID());
			    queryMap.put("partyLeagueMember", partyLeagueMember);
				List<PartyMemberEvaluation> datalist = dyxfzsService.getDybList(queryMap);
				Semester semester = dyxfzsService.queryByPK(partyMemberEvaluation.getSemId());	
				// 得到所有打分项
				List<PartyEvalItem> evalItems = dyxfzsService.getListGrade();
				request.setAttribute("PartyMemberEvaluation", datalist.get(0));
				request.setAttribute("semester", semester);
				request.setAttribute("evalItems", evalItems);
				return "zyc/dyxfzs/view";				
		   }
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	/**
	 * 删除党员信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
					list.add((Integer.valueOf(idList[i])));
				
			}
			if (list.size() != 0) {
				dyxfzsService.delete(list);
			}
			BaseController.setParameter("msg", "删除成功");
			return "redirect:list";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}
	
	
	/**
	 * 跳转到打分项目设置
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "gradelist",method = RequestMethod.GET)
	public String grade(ModelMap model, HttpServletRequest request) {			
			return "zyc/dyxfzs/gradelist";
	}
	 /**
     * 获取打分项目列表分页数据
     * @param model
     * @param request
     * @param pageSize
     * @param currentPage
     * @param partyBranch
     * @return
     */
	@RequestMapping(value="getgradeListData",method=RequestMethod.POST)
	@ResponseBody
	public ResponseResult getgradeListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,  PartyEvalItem partyEvalItem) {
		System.out.println(pageSize + currentPage);
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "itemId", "asc");
		partyEvalItem.setOrderField((String) request.getAttribute("orderField"));
		partyEvalItem.setOrderFlag((String) request.getAttribute("orderFlag"));
		getClass();
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("partyEvalItem",partyEvalItem);
		PaginationBean<PartyEvalItem> paginationBean = dyxfzsService.getgradeListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}
	/**
	 * 添加打分信息
	 * @param model
	 * @param request
	 * @param pM
	 * @return
	 */
	@RequestMapping(value = "insertgarde",method=RequestMethod.POST)
	public String insertgarde(ModelMap model, HttpServletRequest request, PartyEvalItem partyEvalItem) {
		try {
			partyEvalItem.setgID("1");
			partyEvalItem.setItemOrder(1);
			dyxfzsService.insertgarde(partyEvalItem);
			return "redirect:gradelist";				
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	/**
	 * 删除打分信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deletegrade", method = RequestMethod.POST)
	public String deletegrade(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
					list.add((Integer.valueOf(idList[i])));
				
			}
			if (list.size() != 0) {
				dyxfzsService.deletegrade(list);
			}
			BaseController.setParameter("msg", "删除成功");
			return "redirect:gradelist";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}
	
	/**
	 * 下载党员个人先锋指数
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_dzb")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,PartyLeagueMember pM2) throws Exception {
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			String semId = request.getParameter("semId");
		    queryMap.put("partyLeagueMember", pM2);
			List<PartyMemberEvaluation> datalist = dyxfzsService.getDybList(queryMap);
			String[][] title_name = { { "id", "姓名","性别", "工号", "所在党支部", "评定学期", "分数","党员类别","党籍状态","身份证号",
				"学历","民族","联系电话"} };
			String[] title_style = { "hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25", "hwzs_16_bold_25",
					"hwzs_16_bold_25","hwzs_16_bold_25","kt_12_bold_18","kt_12_bold_18", "hwzs_16_bold_25","hwzs_16_bold_25",
					"hwzs_16_bold_25","hwzs_16_bold_25"};
			String fileName = "党员个人先锋指数信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyMemberEvaluation res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("dYID", res.getzSID());
					map.put("xM", res.getPartyLeagueMember().getxM()); 
					map.put("xB", res.getPartyLeagueMember().getxB());
					map.put("gH", res.getPartyLeagueMember().getgH());
					map.put("dZBID", res.getPartyLeagueMember().getPartyBranch().getdZBMC());
					map.put("semId", res.getSemId());
					map.put("totalScore", res.getTotalScore());
					if(res.getPartyLeagueMember().getdYLB() == "1") {
						map.put("dYLB", "正式党员");
					} else  if(res.getPartyLeagueMember().getdYLB() == "2") {
						map.put("dYLB", "预备党员");
					}
					if(res.getPartyLeagueMember().getdJZT() == "1") {
						map.put("dJZT", "正常");						
					} else if(res.getPartyLeagueMember().getdJZT() == "0") {
						map.put("dJZT", "停止党籍");						
					}
					map.put("sFZH", res.getPartyLeagueMember().getsFZH());
					map.put("wHCD", res.getPartyLeagueMember().getwHCD());
					map.put("mZ", res.getPartyLeagueMember().getmZ());
					map.put("lXDH", res.getPartyLeagueMember().getlXDH());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "党员个人先锋指数信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
	
	
	
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}	
}
